package com.jxb.test20241216;

public class Search {

    public static void main(String[] args) {

    }

    //循环迭代的方式
    public int search(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = (start + end)/2;
            if (target > nums[mid]) {
                start = mid + 1;
            }else if (target < nums[mid]) {
                end = mid - 1;
            }else {
                return mid;
            }
        }
        return -1;
    }

    //递归
    public int search1(int[] nums, int target) {
        return searchNums(nums,0,nums.length-1,target);
    }

    private int searchNums(int[] nums, int start, int end, int target) {
        int mid = (start + end)/2;
        if (start <= end) {
            if (target > nums[mid]) {
                return searchNums(nums,mid+1,end,target);
            }else if (target < nums[mid]) {
                return searchNums(nums,start,mid-1,target);
            }else {
                return mid;
            }
        }
        return 0;
    }
}
